package com.learn.boot.xss.config;

import com.learn.boot.xss.filter.MateRequestFilter;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.DispatcherType;

/**
 * 过滤器配置类
 *
 * @author: MI
 * @email: 448341911@qq.com
 * @createDate: 2023/11/12 21:43
 * @updateUser: MI
 * @updateDate: 2023/11/12 21:43
 * @updateRemark: 修改内容
 * @version: v1.0
 */
@Configuration
@AllArgsConstructor
@EnableConfigurationProperties({RequestProperties.class, XssProperties.class})
public class XssRequestAutoConfiguration {


    private final RequestProperties requestProperties;

    private final XssProperties xssProperties;

    @Bean
    public FilterRegistrationBean shiroFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new DelegatingFilterProxy("shiroFilter"));
        //过滤所有路径
        registration.addUrlPatterns("/*");
        //过滤器名称
        registration.setName("shiroFilter");
        //优先级，越低越优先
        registration.setOrder(Integer.MAX_VALUE - 1);
        return registration;
    }

    /**
     * 全局过滤器
     */
    @Bean
    @ConditionalOnProperty(prefix = XssProperties.PREFIX, name = "enable", havingValue = "true", matchIfMissing = false)
    public FilterRegistrationBean xssFilterRegistration() {
        MateRequestFilter xssFilter = new MateRequestFilter();
        xssFilter.setEnableSqlFilter(xssProperties.isSqlFilter());
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new MateRequestFilter(requestProperties, xssProperties));
        registration.addUrlPatterns(xssProperties.getUrlPatterns());
        registration.setName(xssProperties.getName());
        registration.setOrder(xssProperties.getOrder());
        return registration;
    }

}
